package cn.hnucm.handler;

import cn.hnucm.service.LoginService;
import cn.hnucm.utils.Result;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

/**
 * @Author:liweihua
 * @Description:    登录失败处理器
 * @Date: 11:30$ 2021/12/18/018$
 * @Modified:
 */
public class FailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
        PrintWriter out = response.getWriter();
        //设置返回请求头
        //设置缓存区编码为UTF-8编码格式
        response.setCharacterEncoding("UTF-8");
//在响应中主动告诉浏览器使用UTF-8编码格式来接收数据
        response.setHeader("Content-Type", "application/json;charset=UTF-8");
//可以使用封装类简写Content-Type，使用该方法则无需使用setCharacterEncoding
        response.setContentType("application/json;charset=UTF-8");
        out.write(JSONObject.toJSONString(Result.error("登录失败，账号密码错误")));
        out.flush();
        out.close();
    }
}
